import 'dart:math';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:mp_chart/mp/chart/line_chart.dart';
import 'package:mp_chart/mp/controller/line_chart_controller.dart';
import 'package:mp_chart/mp/core/axis/axis_base.dart';
import 'package:mp_chart/mp/core/common_interfaces.dart';
import 'package:mp_chart/mp/core/data/line_data.dart';
import 'package:mp_chart/mp/core/data_interfaces/i_line_data_set.dart';
import 'package:mp_chart/mp/core/data_set/line_data_set.dart';
import 'package:mp_chart/mp/core/description.dart';
import 'package:mp_chart/mp/core/entry/entry.dart';
import 'package:mp_chart/mp/core/enums/legend_horizontal_alignment.dart';
import 'package:mp_chart/mp/core/enums/legend_orientation.dart';
import 'package:mp_chart/mp/core/enums/legend_vertical_alignment.dart';
import 'package:mp_chart/mp/core/enums/x_axis_position.dart';
import 'package:mp_chart/mp/core/highlight/highlight.dart';
import 'package:mp_chart/mp/core/value_formatter/value_formatter.dart';

/**
 *
 * @ProjectName:    chart_widget
 * @ClassName:      chart_page
 * @Description:    dart类作用描述
 * @Author:         孙浩
 * @QQ:             243280864
 * @CreateDate:     2021/9/15 10:07 PM
 */

class ChartWidget extends StatefulWidget {
  final List<List<AppChartData>>? dataList;

  ChartWidget({@required this.dataList});

  @override
  _State createState() => _State();
}

class _State extends State<ChartWidget>
    implements OnChartGestureListener, OnChartValueSelectedListener {
  LineChartController _lineChartController = LineChartController();

  @override
  void initState() {
    super.initState();
    initControl();
    initData();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Column(
        children: [
          Container(
            decoration: BoxDecoration(
                gradient: LinearGradient(
                    begin: Alignment.topCenter,
                    end: Alignment.bottomCenter,
                    colors: [Color(0XFF464760), Color(0XFF181928)])),
            child: LineChart(_lineChartController),
            height: 410,
          ),
        ],
      ),
    );
  }

  @override
  void onChartDoubleTapped(double positionX, double positionY) {}

  @override
  void onChartScale(
      double positionX, double positionY, double scaleX, double scaleY) {}

  @override
  void onChartSingleTapped(double positionX, double positionY) {}

  @override
  void onChartTranslate(
      double positionX, double positionY, double dX, double dY) {}

  @override
  void onNothingSelected() {}

  @override
  void onValueSelected(Entry e, Highlight h) {}

  void initControl() {
    var desc = Description()..enabled = false;
    _lineChartController = LineChartController(
        drawMarkers: false,
        extraRightOffset: 10,
        legendSettingFunction: (legend, controller) {
          //设置图例,无法使用当前建议自定义
          legend
            ..verticalAlignment = (LegendVerticalAlignment.BOTTOM)
            ..horizontalAlignment = (LegendHorizontalAlignment.CENTER)
            ..orientation = (LegendOrientation.HORIZONTAL)
            ..textColor = Colors.white.withOpacity(.6)
            ..formToTextSpace = 4
            ..textSize = 10
            ..drawInside = (false);
        },
        axisRightSettingFunction: (axisRight, controller) {
          axisRight
            ..drawAxisLine = (false)
            ..drawLabels = false
            ..drawGridLines = (false);
        },
        axisLeftSettingFunction: (axisRight, controller) {
          axisRight
            ..textColor = Colors.white.withOpacity(.3)
            ..setValueFormatter(MyValueFormatter())
            ..drawAxisLine = (false)
            ..drawLabels = true
            ..drawGridLines = (false);
        },
        xAxisSettingFunction: (xAxis, controller) {
          xAxis
            ..drawAxisLine = (false)
            ..position = XAxisPosition.BOTTOM
            ..textColor = Colors.white.withOpacity(.3)
            ..setValueFormatter(MyValueTimeFormatter())
            ..drawGridLines = (false);
        },
        drawGridBackground: false,
        backgroundColor: Colors.transparent,
        description: desc);
  }

  void initData() {
    List<ILineDataSet>? list = widget.dataList?.map((e) {
      for (int i = 0; i < e.length; i++) {}
      List<Entry> entryList = e.map((e) {
        Entry entry = Entry(
            x: (e.time.millisecondsSinceEpoch).toDouble(),
            y: e.value,
            data: e.time);
        return entry;
      }).toList();
      LineDataSet d = new LineDataSet(entryList, "${getName(e.first)}");
      d.setLineWidth(2.5);
      d.setCircleRadius(4);
      d.setValueTextSize(0);
      d.setValueTextColor(Colors.transparent);
      d.setCircleHoleRadius(4);
      d.setDrawHighlightIndicators(false);
      d.setColor1(getColor(e.first));
      d.setCircleColor(getColor(e.first));
      return d;
    }).toList();
    if (list != null) {
      _lineChartController.data = LineData.fromList(list);
    }
    setState(() {});
  }

  ///图标颜色
  Color getColor(AppChartData data) {
    Color color = Colors.transparent;
    switch (data.type) {
      case ChartType.sport:
        color = Color(0xffFF2242);
        break;
      case ChartType.sportReal:
        color = Color(0xff24EDD1);
        break;
      case ChartType.food:
        color = Color(0xffB57DFF);
        break;
      case ChartType.foodReal:
        color = Color(0xff858BEC);
        break;
    }
    return color;
  }

  ///列表名称
  String getName(AppChartData data) {
    String name = "";
    switch (data.type) {
      case ChartType.sport:
        name = "运动计划消耗";
        break;
      case ChartType.sportReal:
        name = "运动实际消耗";
        break;
      case ChartType.food:
        name = "饮食计划摄入";
        break;
      case ChartType.foodReal:
        name = "饮食实际摄入";
        break;
    }
    return name;
  }
}

class MyValueFormatter extends ValueFormatter {
  @override
  String getFormattedValue1(double value) {
    return "$value kcal　　";
  }

  @override
  String getAxisLabel(double value, AxisBase axis) {
    return "$value kcal　　";
  }
}

class MyValueTimeFormatter extends ValueFormatter {
  @override
  String getFormattedValue1(double value) {
    DateTime dateTime = DateTime.fromMillisecondsSinceEpoch(value.toInt());
    String month =
        dateTime.month > 10 ? "${dateTime.month}" : "0${dateTime.month}";
    String day = dateTime.day > 10 ? "${dateTime.day}" : "0${dateTime.day}";
    return month + "/" + day;
  }

  @override
  String getAxisLabel(double value, AxisBase axis) {
    DateTime dateTime = DateTime.fromMillisecondsSinceEpoch(value.toInt());
    String month =
        dateTime.month > 10 ? "${dateTime.month}" : "0${dateTime.month}";
    String day = dateTime.day > 10 ? "${dateTime.day}" : "0${dateTime.day}";
    return month + "/" + day;
  }
}

class AppChartData {
  ChartType type = ChartType.food;
  double value = 0.0;
  DateTime time;

  AppChartData(this.type, this.value, this.time);
}

enum ChartType {
  sport,
  sportReal,
  food,
  foodReal,
}
